<template>
  <div class="divBox">
    <el-card class="box-card" shadow="hover">
      <template v-slot:header>
        <el-tabs v-model="tableFrom.type" @tab-click="seachList">
          <el-tab-pane v-for="item in head" :key="item.type" :label="`${item.label} ${item.count > 0 ? '(' + item.count + ')' : ''}`" :name="`${item.type}`"></el-tab-pane>
        </el-tabs>

        <div class="container">
          <el-form size="small" label-width="72px">
            <el-row :gutter="24">
              <el-col v-bind="grid">
                <el-form-item label="商品分类：">
                  <el-cascader v-model="tableFrom.cateId" :options="merCateList" :props="merCateProps" clearable @change="handleChange" style="width: 100%;" />
                </el-form-item>
              </el-col>
              <el-col v-bind="grid">
                <el-form-item label="商品搜索：">
                  <el-input v-model="tableFrom.keyword" placeholder="请输入商品名称,关键字,ID" size="small" class="search-select" clearable>
                    <template v-slot:append>
                      <el-button type="success" icon="el-icon-search" size="small" @click="seachKeywordList" />
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="$router.push(`${customRouter}/product/add_product`)">添加商品</el-button>
        <el-button size="small" type="success" style="display: none">商品采集</el-button>
        <el-tooltip
          v-if="tableType"
          class="ml10"
          effect="dark"
          content="本页至少选中一项"
          placement="bottom"
          :disabled="!disabled"
        >
          <div style="display: inline-block;">
            <el-button size="small" :disabled="disabled" @click="onDismountBatch" v-text="tableType" />
          </div>
        </el-tooltip>
        <el-tooltip
          class="ml10"
          effect="dark"
          content="本页至少选中一项"
          placement="bottom"
          :disabled="!disabled"
        >
          <div style="display: inline-block;">
            <el-button icon="el-icon-upload2" :loading="downloadLoading" size="small" :disabled="disabled" @click="handleDownload">导出</el-button>
          </div>
        </el-tooltip>
      </template>

      <el-table
        v-loading="listLoading"
        :data="tableData.data"
        size="small"
        style="width: 100%"
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="expand">
          <template slot-scope="{ row }">
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item v-if="row.cateStr" label="商品分类：">
                <span v-text="row.cateStr" />
              </el-form-item>
              <el-form-item label="市场价：">
                <span>{{ row.marketPrice | NumFormat }}</span>
              </el-form-item>
              <el-form-item label="成本价：">
                <span>{{ row.costPrice | NumFormat }}</span>
              </el-form-item>
              <el-form-item v-if="row.collectCount" label="收藏：">
                <span>{{ row.collectCount }}</span>
              </el-form-item>
              <el-form-item label="虚拟销量：">
                <span>{{ row.ficti }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>

        <el-table-column type="selection" width="60"></el-table-column>
        <el-table-column prop="id" label="商品ID" width="80"></el-table-column>

        <el-table-column
          label="商品图"
          min-width="80"
        >
          <template slot-scope="{ row }">
            <div class="demo-image__preview">
              <div class="tabBox_img" v-viewer>
                <img v-lazy="$uploadURL(row.image)" />
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="title" label="商品名称" min-width="250"></el-table-column>
        <el-table-column prop="price" label="商品售价" min-width="90"></el-table-column>
        <el-table-column prop="sales" label="销量" sortable min-width="90"></el-table-column>
        <el-table-column prop="stock" label="库存" min-width="80"></el-table-column>
        <el-table-column prop="sort" label="排序" min-width="70"></el-table-column>

        <el-table-column
          label="状态"
          width="100"
        >
          <template slot-scope="scope">
            <el-switch
              v-model.number="scope.row.isShow"
              :active-value="1"
              :inactive-value="0"
              active-text="上架"
              inactive-text="下架"
              class="status"
              @change="onChangeIsShow(scope.row.isShow, scope.row.id)"
            />
          </template>
        </el-table-column>

        <el-table-column
          fixed="right"
          label="操作"
          align="center"
          width="310"
        >
          <template slot-scope="{ row }">
            <el-button type="text" size="small" @click="$router.push(`${ customRouter }/product/add_product/${ row.id }`)">编辑</el-button>
            <el-divider direction="vertical"></el-divider>
<!--            <el-button type="text" size="small" @click="$router.push(`${ customRouter }/product/add_product/${ row.id }/1`)">查看</el-button>-->
            <el-button type="text" size="small" @click="look(row.id)">详情</el-button>
            <el-divider direction="vertical"></el-divider>
            <el-button type="text" size="small" @click="$router.push({ name: 'product_product_reply', params: { id: row.id } })">查看评论</el-button>
            <el-divider direction="vertical"></el-divider>
            <el-button type="text" size="small" @click="handleDelete(row.id, tableFrom.type)" v-text="tableFrom.type == 5 ? '恢复商品' : '移动到回收站'" />
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="pagination.total > 0"
        :total="pagination.total"
        :page.sync="pagination.currentPage"
        :limit.sync="pagination.limit"
        :page-sizes="[10, 20, 30, 50]"
        @pagination="pageChange"
      />
    </el-card>
    <!-- 查看 -->
    <look-product v-if="isProductBox" :productId="productId" @lookBack="isProductBox = false"></look-product>
  </div>
</template>

<script>
  import lookProduct from './components/lookProduct';

import {
  productListApi,
  patchStateApi,
  categoryApi,
  productDeleteApi,
  getHeadCountApi
} from '@/api/store';
import { mapGetters } from 'vuex';

import { getToken } from '@/utils/auth'

export default {
  name: "product_productList",
  components: {
    lookProduct
  },
  data() {
    return {
      grid: {
        xl: 5,
        lg: 7,
        md: 12,
        sm: 24,
        xs: 24
      },
      downloadLoading: false,
      listLoading: false,
      tableFrom: {
        type: '1',
        cateId: 0,
        keyword: ''
      },
      head: [
        {
          label: '出售中的商品',
          type: 1,
          count: 0
        },
        {
          label: '仓库中的商品',
          type: 2,
          count: 0
        },
        {
          label: '已经售馨商品',
          type: 3,
          count: 0
        },
        {
          label: '警戒库存商品',
          type: 4,
          count: 0
        },
        {
          label: '回收站的商品',
          type: 5,
          count: 0
        }
      ],
      merCateList: [],
      merCateProps: {
        children: 'children',
        label: 'name',
        value: 'id',
        emitPath: false
      },
      disabled: true,
      tableData: {
        data: []
      },
      pagination: {
        total: 0,
        currentPage: 1,
        limit: 10
      },
      multipleSelection: [],
      headNum: {},
      // 查看详情
      isProductBox: false,
      productId: 0
    }
  },
  computed: {
    ...mapGetters([
      'customRouter'
    ]),
    tableType() {
      if (this.tableFrom.type == 1) return '批量下架';
      else if (this.tableFrom.type == 2) return '批量上架';
      return
    }
  },
  mounted() {
    this.getList()
    this.getCategorySelect()
    this.headCount()
    console.log('**********：',getToken())
  },
  methods: {
    /**
     * 查看
     * @param id 产品ID
     */
    look(id) {
      this.productId = id;
      this.isProductBox = true;
    },
    // 数量统计
    headCount() {
      getHeadCountApi().then(res => {
        this.head.forEach((item) => {
          if (item.type === 1) item.count = res.onTheShelf_Count
          else if (item.type === 2) item.count = res.offTheShelf_Count
          else if (item.type === 3) item.count = res.soldOut_Count
          else if (item.type === 4) item.count = res.alertInventory_Count
          else if (item.type === 5) item.count = res.del_Count
        })
      }).catch(() => {
        this.$message.error('数量错误')
      })
    },
    // 导出
    handleDownload() {
      this.downloadLoading = true

      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['ID', '标题', '分类', '商品价格', '库存', '销量', '浏览量']
        const filterVal = ['id', 'title', 'cateStr', 'price', 'stock', 'sales', 'browse']
        const list = this.multipleSelection
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: `商品导出_${new Date().getTime()}`,
          autoWidth: true,
          bookType: 'xlsx'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'cateStr') {
          return v[j].split('/').join(',')
        } else {
          return v[j]
        }
      }))
    },
    // 批量下架功能
    onDismountBatch() {
      this.patchState(this.tableFrom.type == 1 ? 0 : 1, this.multipleSelection.map((item) => item.id).join(','))
    },
    // 当表格选择项发生变化时
    handleSelectionChange(list) {
      this.multipleSelection = list
      list.length > 0 ? this.disabled = false : this.disabled = true
    },
    // 回收站
    handleDelete(id, type) {
      const t = type != 5 ? '移入' : '移出'

      const confirmText = type != 5 ? ['确定要移入回收站吗？', '移入回收站后将无法恢复，请谨慎操作！'] : ['确定要移出回收站吗？', '请谨慎操作！']
      const h = this.$createElement

      this.$confirm(`${t}回收站`, {
        title: `${t}回收站`,
        message: h('div', null, confirmText.map((item) => h('p', null, item))),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        productDeleteApi(id).then(res => {
          this.$message.success(`成功${t}到回收站!`)
          this.getList()
          this.headCount()
        }).catch(() => {
          this.$message.error(`${t}到回收站失败!请稍后再试`)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: `已取消${t}回收站`
        })
      })
    },
    // 关键词搜索
    seachKeywordList() {
      this.pagination.currentPage = 1
      this.getList()
    },
    // 分类框改变时
    handleChange() {
      this.pagination.currentPage = 1
      this.getList()
    },
    // 商品分类
    getCategorySelect() {
      categoryApi({ isShow: 1 }).then(res => {
        this.merCateList = res
      }).catch(err => {
        this.$message.error(err.content || '获取分类失败!')
      })
    },
    // 点击Tabs切换数据
    seachList() {
      this.pagination.currentPage = 1
      this.getList()
    },
    // 分页
    pageChange(data) {
      this.pagination.currentPage = data.page
      this.getList()
    },
    patchState(isShow, id) {
      patchStateApi({ 'op': 'replace', 'path': '/isShow', 'value': isShow, 'id': id.toString() }).then(res => {
        this.$message.success(isShow ? '上架成功!' : '下架成功!')
        this.getList()
        this.headCount()
      }).catch(() => {
        isShow = Number(!isShow)
      })
    },
    // 状态改变时
    onChangeIsShow(isShow, id) {
      this.patchState(isShow, id)
    },
    // 读取数据
    getList() {
      // 打开表格加载
      this.$set(this, 'listLoading', true)
      productListApi({
        pageNumber: this.pagination.currentPage,
        pageSize: this.pagination.limit,
        queryType: this.tableFrom.type,
        cateId: this.tableFrom.cateId,
        keyword: this.tableFrom.keyword,
        orderBy: 'createDateUtc desc'
      }).then(res => {
        const list = res.data
        this.tableData.data = list
        this.pagination.total = res.head ? res.head.totalCount : 0
        this.$set(this, 'listLoading', false)
      }).catch((err) => {
        this.$set(this, 'listLoading', false)
        this.$set(this.tableData, 'data', [])
        this.$set(this.pagination, 'total', 0)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .divBox {
    ::v-deep .demo-table-expand {
      label.el-form-item__label {
        width: 82px;
      }
      .el-form-item {
        width: 32.33% !important;
      }
    }
    .demo-image__preview {
      .tabBox_img {
        cursor: pointer;
        display: block;
      }
    }
    .el-form-item--small.el-form-item {
      margin-bottom: 15px;
    }
    ::v-deep .el-table__expanded-cell[class*=cell]{
      padding:20px 50px !important;
    }
  }
</style>
